<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>实时通讯</title>
    <!-- 引入 RuoYi 公共样式和 LayUI -->
    <th:block th:include="include :: header('实时通讯')"/>
    <style>
        .im-container {
            display: flex;
            height: 80vh;
            border: 1px solid #e6e6e6;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
            background: #fff;
        }

        /* 会话列表样式 */
        .session-list {
            width: 280px;
            background: #f8f9fa;
            border-right: 1px solid #e6e6e6;
            overflow-y: auto;
        }

        .session-item {
            padding: 15px;
            cursor: pointer;
            display: flex;
            align-items: center;
            transition: all 0.3s;
            border-bottom: 1px solid #eee;
        }

        .session-item:hover {
            background: #f1f1f1;
        }

        .session-item.active {
            background: #3c8dbc;
            color: white;
            border-left: 4px solid #2a6496;
        }

        .session-item img {
            width: 45px;
            height: 45px;
            border-radius: 50%;
            margin-right: 12px;
            border: 2px solid #e6e6e6;
        }

        /* 聊天区域 */
        .chat-box {
            flex: 1;
            display: flex;
            flex-direction: column;
        }

        .chat-header {
            padding: 10px;
            border-bottom: 1px solid #e6e6e6;
            display: flex;
            align-items: center;
            background: #fff;
        }
        .chat-header img {
            margin-right: 10px;
            border-radius: 50%;
        }

        /* 消息区域 */
        .message-area {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            background: #f5f6fa;
        }

        .message-bubble {
            max-width: 65%;
            padding: 12px 16px;
            margin: 10px;
            border-radius: 15px;
            position: relative;
            font-family: 'Segoe UI', sans-serif;
            line-height: 1.5;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
        }

        .self {
            background: #3c8dbc;
            color: white;
            margin-left: auto;
            border-bottom-right-radius: 5px;
        }

        .other {
            background: white;
            color: #676a6c;
            margin-right: auto;
            border: 1px solid #e6e6e6;
            border-bottom-left-radius: 5px;
        }

        /* 输入框区域 */
        .input-box {
            height: 100px;
            border-top: 1px solid #e6e6e6;
            padding: 15px;
            background: #fff;
            position: relative;
        }

        #inputMsg {
            width: 100%;
            height: 100%;
            border: none;
            resize: none;
            padding: 12px;
            font-size: 14px;
            border: 1px solid #e6e6e6;
            border-radius: 6px;
        }

        #inputMsg:focus {
            outline: none;
            border-color: #3c8dbc;
            box-shadow: 0 0 0 2px rgba(60, 141, 188, 0.2);
        }

        /* 滚动条样式 */
        ::-webkit-scrollbar {
            width: 6px;
        }

        ::-webkit-scrollbar-track {
            background: #f1f1f1;
        }

        ::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 4px;
        }

        ::-webkit-scrollbar-thumb:hover {
            background: #3c8dbc;
        }

        /* 时间戳样式 */
        .message-time {
            font-size: 12px;
            color: #999;
            text-align: center;
            margin: 10px 0;
        }

        .online-status {
            color: green;
            margin-left: 10px;
        }

        .offline-status {
            color: gray;
            margin-left: 10px;
        }


    /*    消息气泡样式*/
        .message-bubble {
            display: flex;
            align-items: flex-start;
            margin: 10px;
        }
        .message-avatar {
            margin-right: 10px;
            border-radius: 50%;
        }
        .message-content {
            max-width: 70%;
        }
        .message-sender {
            font-size: 12px;
            color: #666;
            margin-bottom: 4px;
        }
        .message-text {
            padding: 8px 12px;
            border-radius: 8px;
            background: #fff;
            border: 1px solid #e6e6e6;
        }
        .message-time {
            font-size: 10px;
            color: #999;
            margin-top: 4px;
        }
        .self .message-text {
            background: #3c8dbc;
            color: white;
            border: none;
        }
    </style>
</head>
<body>
<input type="hidden" th:value="${loginUser.userName}" id="username" />
<div class="im-container">
    <!-- 左侧会话列表 -->
    <div class="session-list">
        <!-- 使用 Thymeleaf 迭代用户列表 -->
        <div class="session-item" th:classappend="${session.activeUser == user.userId} ? 'active'"
             th:data-id="${user.userId}" th:each="user : ${userList}">
            <img height="40" th:src="@{${user.userAvatar}}" width="40"/>
            <span th:text="${user.userName}"></span>
            <span th:class="${user.online} ? 'online-status' : 'offline-status'"
                  th:text="${user.online} ? '在线' : '离线'"></span>
        </div>
    </div>

    <!-- 右侧聊天区域 -->
    <div class="chat-box">
        <!-- 聊天框顶部 -->
        <div class="chat-header">
            <img id="chatAvatar" src="" width="40" height="40"/>
            <span id="chatName"></span>
        </div>
        <!-- 消息区域 -->
        <div class="message-area" id="messageArea"></div>
        <!-- 输入框区域 -->
        <div class="input-box">
            <textarea id="inputMsg" placeholder="输入消息..."></textarea>
        </div>
    </div>
</div>

<!-- 引入 jQuery 和 LayUI -->
<th:block th:include="include :: footer"/>
<script>
    var nettyUrl = "ws://localhost:9326/ws";
    var userListUrl = ctx + "system/im/userList";
    var currentUser = [[${currentUserId}]];
    // var currentUserName = [[${currentUserName}]];
    var currentSession = "";
    $(function () {
        let ws; // WebSocket 连接对象

        // 初始化 WebSocket 连接
        function initWebSocket() {
            ws = new WebSocket(nettyUrl);

            ws.onopen = function () {
                console.log('WebSocket 连接成功');
                // 发送身份认证（使用 RuoYi 登录 Token）
                // const token = localStorage.getItem('ruoyi-token');
                // console.log('token====>', token);
                ws.send(JSON.stringify({
                    type: 'auth',
                    userId: currentUser
                }));
            };

            ws.onmessage = function (event) {
                console.log('WebSocket 收到消息:', event.data);
                const msg = JSON.parse(event.data);
                if (msg.type === 'chat') {
                    appendMessage(msg);
                }
                if (msg.type === 'status') {
                    updateUserStatus(msg.userId, msg.online);
                }
            };

            ws.onerror = function (error) {
                console.error('WebSocket 错误:', error);
            };
        }

        //在线离线状态更新
        function updateUserStatus(userId, isOnline) {
            console.log('更新用户状态:', userId, isOnline);
            const $userItem = $(`.session-item[data-id="${userId}"]`);
            const $status = $userItem.find('.online-status, .offline-status');
            if (isOnline) {
                $status.removeClass('offline-status').addClass('online-status').text('在线');
            } else {
                $status.removeClass('online-status').addClass('offline-status').text('离线');
            }
        }

        // 会话项点击事件
        $('.session-list').on('click', '.session-item', function () {
            // 获取用户信息
            const userId = $(this).data('id'); // 用户ID
            const userName = $(this).find('span').first().text(); // 用户昵称
            const userAvatar = $(this).find('img').attr('src'); // 用户头像

            // 更新聊天框顶部信息
            $('#chatAvatar').attr('src', userAvatar);
            $('#chatName').text(userName);

            // 设置当前会话
            currentSession = userId;

            // 加载历史消息
            loadHistory(userId);

            // 高亮选中用户
            $('.session-item').removeClass('active');
            $(this).addClass('active');
        });

        // 加载历史消息
        function loadHistory(targetUserId) {
            $.ajax({
                url: ctx + "system/im/history",
                type: "POST",
                data: {targetUserId: targetUserId},
                success: function (res) {
                    if (res.code === 200) {
                        $('#messageArea').html('');
                        res.data.forEach(msg => {
                            appendMessage(msg);
                        });
                    }
                }
            });
        }

        // 加载会话列表
        function loadUserList() {
            $.ajax({
                url: userListUrl,
                type: 'POST',
                success: function (res) {
                    if (res.code === 0) {
                        renderUserList(res.data);
                    } else {
                        console.error('获取用户列表失败:', res.msg);
                    }
                },
                error: function (err) {
                    console.error('请求失败:', err);
                }
            });
        }

        // 渲染用户列表
        function renderUserList(userList) {
            const $sessionList = $('.session-list');
            $sessionList.empty();
            userList.forEach(user => {
                console.log('用户列表元素:', user);
                const statusClass = user.online ? 'online-status' : 'offline-status';
                const statusText = user.online ? '在线' : '离线';
                const itemHtml = `
                <div class="session-item" data-id="${user.userId}">
                    <img src="${user.userAvatar}" width="40" height="40"/>
                    <span>${user.userName}</span>
                    <span class="${statusClass}">${statusText}</span>
                </div>
            `;
                $sessionList.append(itemHtml);
            });
        }

        // 初始化
        loadUserList();

        // 渲染消息
        function appendMessage(msg) {
            const isSelf = msg.sender === currentUser;
            const formattedTime = formatTime(msg.timestamp);
            const userName = $("#username").val();
            const bubbleHtml = `
        <div class="message-bubble ${isSelf ? 'self' : 'other'}">
            <img class="message-avatar" src="${msg.avatar}" width="30" height="30"/>
            <div class="message-content">
                <div class="message-sender">${userName}</div>
                <div class="message-text">${msg.content}</div>
                <div class="message-time">${formattedTime}</div>
            </div>
        </div>
    `;
            $('#messageArea').append(bubbleHtml);
            scrollToBottom();
        }

        // 发送消息
        function sendMessage() {
            const content = $('#inputMsg').val().trim();
            if (!content) return;

            const message = {
                type: 'chat',
                to: currentSession,
                content: content,
                timestamp: new Date().getTime(),

            };

            ws.send(JSON.stringify(message));
            appendMessage({...message, sender: currentUser});
            $('#inputMsg').val('');
        }

        // 滚动到底部
        function scrollToBottom() {
            const container = $('#messageArea')[0];
            container.scrollTop = container.scrollHeight;
        }

        // 绑定发送事件
        $('#inputMsg').on('keyup', function (e) {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });

        // 时间格式化函数
        function formatTime(timestamp) {
            return new Date(timestamp).toLocaleString();
        }

        // 初始化
        initWebSocket();
    });
</script>
</body>
</html>